from datetime import date, datetime, timedelta

from django.db import transaction
from django.shortcuts import render
from django.db.models import Count, Max, Min
from django.core.exceptions import ObjectDoesNotExist

# Create your views here.

from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework import status
from rest_framework import filters
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema, coreapi
from coreapi import Field
import coreschema
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import pytz

from dateutil import parser


from django_filters.rest_framework import DjangoFilterBackend

from .models import *
from .serializers import *


from django.db.models import Q

import re
import importlib

from rest_framework.schemas.coreapi import AutoSchema
import coreapi

SERIALIZER_MODULE = "ephm_sqlserver_api.serializers"
MODULES = "ephm_sqlserver_api.models"


# Create your views here.
class PowertrainQdasBlockDataQuery(APIView):
    # 设置在API DOC的字段显示
    module_dict = {"M1": {"WVPRUEFER": "201"}, "M2": {"WVPRUEFER": "202"}}
    line_dict = {"A线": {"WVNEST": ["201", "203", "205"]}, "B线": {"WVNEST": ["202", "204", "206"]}}

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="wvteil",
                required=True,
                location="query",
                schema=coreschema.String(description="零件代码，可通过工位、机型、特征获取,如缸体OP20代码为:647"),
            ),
            Field(
                name="wvmerkmal",
                required=True,
                location="query",
                schema=coreschema.String(description="特征代码，可通过工位、机型、特征获取,如缸体OP20-H001-1截面代码为:8"),
            ),
            Field(
                name="module",
                required=False,
                location="query",
                schema=coreschema.Enum(enum=list(module_dict.keys()), description="M1/M2"),
            ),
            Field(
                name="line",
                required=False,
                location="query",
                schema=coreschema.Enum(enum=list(line_dict.keys()), description="A线/B线"),
            ),
            Field(
                name="start_time",
                required=False,
                location="query",
                schema=coreschema.String(description="开始时间，格式:YYYY-MM-DD HH:MM:SS,留空默认:'2025-01-01 00:00:00'"),
            ),
            Field(
                name="end_time",
                required=False,
                location="query",
                schema=coreschema.String(description="结束时间，格式：YYYY-MM-DD HH:MM:SS"),
            ),
            Field(
                name="data_length",
                required=False,
                location="query",
                schema=coreschema.String(description="数据长度，默认150，受时间范围约束"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data = self.qdas_data_query(request)

        # 序列化数据
        return Response(data, status=status.HTTP_200_OK)

    def qdas_data_query(self, request, *args, **kwargs):
        try:
            # 定义数据库连接信息
            wvteil = request.query_params.get("wvteil")
            wvmerkmal = request.query_params.get("wvmerkmal")
            start_time_str = request.query_params.get("start_time", "2025-01-01 00:00:00")
            end_time_str = request.query_params.get("end_time")
            data_length = request.query_params.get("data_length", 150)
            module_str = request.query_params.get("module")
            line_str = request.query_params.get("line")

            print(wvteil, wvmerkmal)

            # 根据你的驱动版本调整，这里使用ODBC Driver 17 for SQL Server为例
            try:
                from django.utils import timezone

                start_time = timezone.datetime.strptime(start_time_str, "%Y-%m-%d %H:%M:%S")
                if timezone.is_naive(start_time):
                    start_time = timezone.make_aware(start_time, timezone=pytz.UTC)
                if end_time_str:
                    end_time = timezone.datetime.strptime(end_time_str, "%Y-%m-%d %H:%M:%S")
                    if timezone.is_naive(end_time):
                        end_time = timezone.make_aware(end_time, timezone=pytz.UTC)
                else:
                    end_time = None
            except ValueError:
                return {"status": "error", "message": "Invalid date format. Use YYYY-MM-DD HH:MM:SS."}

            # 使用 Django 模型进行查询
            fields = [
                "wvteil",
                "wvmerkmal",
                "wvunters",
                "wvwertnr",
                "wvwert",
                "wvattribut",
                "wvpruefer",
                "wvpruefmit",
                "wvmaschine",
                "wvnest",
                "wvdatzeit",
                "wvstianf",
                "wvcharge",
                "wvauftrag",
                "wv0005",
                "wv0009",
                "wv0011",
                "wv0014",
            ]

            queryset = Wertevar.objects.using("qdas_block").filter(wvteil=wvteil, wvmerkmal=wvmerkmal, wvdatzeit__gte=start_time).values(*fields).order_by("-wvdatzeit")

            if end_time:
                queryset = queryset.filter(wvdatzeit__lte=end_time)

            if module_str:
                module = self.module_dict[module_str]["WVPRUEFER"]
                queryset = queryset.filter(wvpruefer=module)

            if line_str:
                nest = self.line_dict[line_str]["WVNEST"]
                queryset = queryset.filter(wvnest__in=nest)

            # 排序并取数量为data_length的记录条数
            if data_length:
                queryset = queryset[: int(data_length)]

            result = list(queryset)

            if result:
                return {"status": "success", "message": "Database connection successful.", "data": result}
            else:
                return {"status": "warning", "message": "Query executed successfully, but no data was returned."}
        except Exception as e:
            print(e)
            error_data = {"status": "error", "message": f"Database connection failed: {str(e)}"}
            return error_data
